package com.changgou.system.utils;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;

public class JwtUtil {
    //设置token有效时间因为一个小时
    public static final Long JWT_TTL = 60*60*1000L;
    //设置秘钥明文
    public  static final String JWT_KEY = "itcast";

    /**
     *  创建Token
     * @date 2019/11/21
     * @param id
     * @param subject
     * @param ttlMillis
     * @return java.lang.String
    **/
    public static String createJWT(String id,String subject,Long ttlMillis){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (ttlMillis==null){
            ttlMillis=JwtUtil.JWT_TTL;
        }
        long expMillis = nowMillis + ttlMillis;
        Date expDate = new Date(expMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)  //唯一的Id
                .setSubject(subject) //主题
                .setIssuer("admin")  //签发者
                .setIssuedAt(now)   //签发时间
                .signWith(signatureAlgorithm,secretKey) //使用HS256对称加密算法签名,第二个参数为秘钥
                .setExpiration(expDate);    //过期时间

        return builder.compact();
    }

    /**
     *  生成加密后的密钥 secketKey
     * @date 2019/11/21
     * @return javax.crypto.SecretKey
    **/
    public static SecretKey generalKey(){
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey,0,encodedKey.length,"AES");
        return key;
    }

    /**
     *  解析
     * @date 2019/11/21
     * @param jwt
     * @return io.jsonwebtoken.Claims
    **/
    public static Claims parseJWT(String jwt) throws Exception{
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
